<?php
namespace lactone\Core\Spider;

use lactone\Core\Models\TaskModel;
use lactone\Core\Object;
use lactone\Core\Models\SpiderModel;

class Spiders extends Object{

    const   Live_Status = 1;
    const   Dead_Status = 0;

    public  $Spiders;

    public  $LiveSpiders;

    /**
     * 从数据库获取有多少蜘蛛已经被注册了
     * @throws \ActiveRecord\RecordNotFound
     */
    public function init(){
    }

    /**
     * 添加一个蜘蛛
     * @param Spider $spider
     */
    public function addSpider(SpiderModel $spider){

    }

    /**
     * 通过ip和port对应蜘蛛，并且把蜘蛛置为有效的
     * @param $ip
     * @param $port
     * @return bool
     */
    public function liveSpider($ip,$port){
          if($Spider = SpiderModel::find(['ip'=>$ip,'port'=>$port])){

              $Spider->update_attributes([
                  'update_at' => time(),
                  'status'    => self::Live_Status
              ]);
          }
    }

    /**
     * 是否存在蜘蛛
     * @param $ip
     * @param $port
     * @return bool
     */
    public function hasSpider($ip,$port){
        if($Spider = SpiderModel::find(['ip'=>$ip,'port'=>$port])){
             return true;
        }
        return false;
    }

    /**
     * 通过id查找对应的id
     */
    public function findById($id){
        return SpiderModel::find($id);
    }

    /**
     * 获取所有的蜘蛛
     * @return mixed
     */
    public function getSpiders(){
        return $this->Spiders;
    }

    /**
     * 获取所有存活的蜘蛛总数
     */
    public function getLiveSpiders(){
        return $this->LiveSpiders;
    }

    /**
     * 获取空闲的蜘蛛
     * @return bool|mixed
     */
    public function getFreeSpider(){
        if($Spiders =  SpiderModel::find_by_sql("SELECT * FROM spider WHERE id = ( SELECT id FROM ( SELECT ( spider.task_run - spider.task_run_done ) AS a, id FROM spider WHERE `status` = ".self::Live_Status." ) AS ab ORDER BY a ASC LIMIT 1 )")){
            return $Spiders[0];
        }
        return false;

    }

    /**
     * 是否存在活着的spider
     */
    public function hasLiveSpider(){

        if($Spiders =  SpiderModel::find_by_sql("select count(*) as count from spider where status =".self::Live_Status)){
            if($Spiders[0]->count > 0 ) return true;
        }

        return true;
    }

    /**
     * 累加任务
     * @param $id
     */
    public function stepAddTask($id){
        SpiderModel::query("update spider set task_run = task_run+1 where id = ".$id);
    }

    /**
     * 累减任务
     * @param $id
     */
    public function stepCutTask($id){
        SpiderModel::query("update spider set task_run_done = task_run_done+1 where id = ".$id);
    }

    /**
     * 累减蜘蛛执行的任务总数，从taskid
     * @param $t_id
     */
    public function stepCutTaskFormTaskId($t_id){
        \Lactone::debug("[".__METHOD__."]task:".$t_id);
        if($task = TaskModel::find($t_id)){
            $this->stepCutTask($task->s_id);
        }
    }
}